package com.ljkj.cordial.chat.util;

import android.content.Context;
import android.text.TextUtils;

import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.AlbumTableBeanDao;
import com.ljkj.cordial.chat.dao.BusinessLeaveTableDao;
import com.ljkj.cordial.chat.dao.ChatContentTableDao;
import com.ljkj.cordial.chat.dao.ChatTableBean;
import com.ljkj.cordial.chat.dao.ChatTableBeanDao;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.FriendTableDao;
import com.ljkj.cordial.chat.dao.GroupMemberTableDao;
import com.ljkj.cordial.chat.dao.GroupTableDao;
import com.ljkj.cordial.chat.dao.LengthMessageTable;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.UserTableBeanDao;
import com.ljkj.cordial.chat.dao.notify.BusinessLeaveTable;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.dao.notify.SysNoticeTable;
import com.nic.view.util.JLog;
import com.nic.view.util.SharedUtils;
import com.yanzhenjie.album.util.AlbumUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DeleteHistoryUtil {
    private static class BUILD {
        public static DeleteHistoryUtil INSTANCE = new DeleteHistoryUtil();
    }

    public static DeleteHistoryUtil getInstance() {
        return BUILD.INSTANCE;
    }

    /**
     * 删除游客用户表
     */
    public void deleteVisitorUser() {
        List<UserTableBean> list = DbController.getInstance().getRead().getUserTableBeanDao().queryBuilder()
                .where(UserTableBeanDao.Properties.UserType.eq(UserTableBean.TYPE_VISITOR)).list();
        List<String> visitors = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (UserTableBean userTableBean : list) {
                visitors.add(userTableBean.getTemporaryId());
            }
            DbController.getInstance().getWrite().getUserTableBeanDao().deleteInTx(list);
            for (String visitor : visitors) {
                if (!TextUtils.isEmpty(visitor)) {
//                    deleteLengthMsgTable(visitor);
                    deleteChat(visitor, Canstants.SINGLE_CHAT, true, true);
                }
            }


        }
    }


    public void deleteChat(String targetId, int fromType, boolean isClearUser, boolean isClearGroup) {
        if (isClearUser) {
            deleteFriend(targetId);
        }
        if (isClearGroup) {
            deleteGroup(targetId);
        }
        List<ChatTableBean> list = fromType == 0 ? DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                .where(ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                        , ChatTableBeanDao.Properties.ChatName.eq(targetId)).list() :
                DbController.getInstance().getRead().getChatTableBeanDao().queryBuilder()
                        .where(ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                                , ChatTableBeanDao.Properties.ChatName.eq(targetId),
                                ChatTableBeanDao.Properties.FromType.eq(fromType)).list();
        if (list != null && !list.isEmpty()) {
            for (ChatTableBean chatTable : list) {
                if (!TextUtils.isEmpty(chatTable.getAlbumId())) {
                    deleteFileTable(Long.parseLong(chatTable.getAlbumId()));
                }
                if (!TextUtils.isEmpty(chatTable.getMsgId())) {
                    deleteLeaveTable(chatTable.getMsgId());
                }
//                DbController.getInstance().getWrite().getChatTableBeanDao().delete(chatTable);
            }
            DbController.getInstance().getWrite().getChatTableBeanDao().deleteInTx(list);
        }
    }

    public void deleteNavChat(String targetId) {
        deleteNavChat(targetId, Canstants.SINGLE_CHAT, true, false);
    }

    public void deleteNavChat(String targetId, int chatType, boolean isClearUser, boolean isClearGroup) {
        if (TextUtils.isEmpty(targetId)) {
            return;
        }
        deleteChat(targetId, chatType, isClearUser, isClearGroup);
        List<ChatContentTable> list = chatType == 0 ? DbController.getInstance().getRead().getChatContentTableDao().queryBuilder()
                .where(ChatContentTableDao.Properties.TargetId.eq(targetId),
                        ChatContentTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).list() :
                DbController.getInstance().getRead().getChatContentTableDao().queryBuilder()
                        .where(ChatContentTableDao.Properties.TargetId.eq(targetId),
                                ChatContentTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId()),
                                ChatContentTableDao.Properties.ChatType.eq(chatType)).list();
//        for (ChatContentTable table : list) {
//            DbController.getInstance().getWrite().getChatContentTableDao().delete(table);
//        }
        DbController.getInstance().getWrite().getChatContentTableDao().deleteInTx(list);
    }

    public void deleteChatHistory() {
        try {
            List<ChatContentTable> list = DbController.getInstance().getRead().getChatContentTableDao()
                    .queryBuilder().where(ChatContentTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).list();
            if (list != null && !list.isEmpty()) {
                for (ChatContentTable contentTable : list) {
                    deleteNavChat(contentTable.getTargetId(), contentTable.getChatType(), false, false);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteGroupMember(String visitorId, String groupId) {
        List<GroupMemberTable> memberList = DbController.getInstance().getRead().getGroupMemberTableDao().queryBuilder()
                .where(GroupMemberTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                        , GroupMemberTableDao.Properties.GroupId.eq(groupId)
                        , GroupMemberTableDao.Properties.GroupMemberUserId.eq(visitorId)).list();
        if (memberList != null && memberList.isEmpty()) {
            DbController.getInstance().getWrite().getGroupMemberTableDao().deleteInTx(memberList);
        }
    }

    public void deleteGroup(String userId) {
        List<GroupTable> list = DbController.getInstance().getRead().getGroupTableDao().queryBuilder()
                .where(GroupTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                        , GroupTableDao.Properties.GroupOwnerId.eq(userId)).list();
        List<String> groupIds = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            for (GroupTable chatTable : list) {
                groupIds.add(chatTable.getGroupId());
            }
            DbController.getInstance().getWrite().getGroupTableDao().deleteInTx(list);
            for (String groupId : groupIds) {
                deleteGroupMember(userId, groupId);
            }
        }
    }

    public void deleteFriend(String visitorId) {
        List<FriendTable> list = DbController.getInstance().getRead().getFriendTableDao().queryBuilder()
                .where(FriendTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                        , FriendTableDao.Properties.FriendUserId.eq(visitorId)).list();
        if (list != null && !list.isEmpty()) {
            DbController.getInstance().getWrite().getFriendTableDao().deleteInTx(list);
        }
    }

    public void deleteFileTable(List<ChatTableBean> chatTables) {
        if (chatTables == null || chatTables.isEmpty()) {
            return;
        }
        for (ChatTableBean chatTable : chatTables) {
            if (!TextUtils.isEmpty(chatTable.getAlbumId())) {
                deleteFileTable(Long.parseLong(chatTable.getAlbumId()));
            }
        }
    }

    public void deleteFileTable(Long fileId) {
        if (fileId <= 0L) {
            return;
        }
        AlbumTableBean chatTable = DbController.getInstance().getRead().getAlbumTableBeanDao().queryBuilder()
                .where(AlbumTableBeanDao.Properties.Id.eq(fileId)
                        , AlbumTableBeanDao.Properties.MMediaType.notEq(AlbumTableBean.TYPE_AVATAR)).unique();
        if (chatTable != null) {
            DbController.getInstance().getWrite().getAlbumTableBeanDao().delete(chatTable);
            if (!TextUtils.isEmpty(chatTable.getMPath())) {
//                AlbumUtils.deleteDirectory(chatTable.getMPath());
                File file = new File(chatTable.getMPath());
                if (file.exists()) {
                    file.delete();
                }
            }
            if (!TextUtils.isEmpty(chatTable.getMThumbPath())) {
//                AlbumUtils.deleteDirectory(chatTable.getMThumbPath());
                File file = new File(chatTable.getMThumbPath());
                if (file.exists()) {
                    file.delete();
                }
            }

        }
    }

    public void deleteLeaveTable(String msgId) {
        List<BusinessLeaveTable> list = DbController.getInstance().getRead().getBusinessLeaveTableDao().queryBuilder()
                .where(BusinessLeaveTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())
                        , BusinessLeaveTableDao.Properties.MsgId.eq(msgId)).list();
        if (list != null && !list.isEmpty()) {
            DbController.getInstance().getWrite().getBusinessLeaveTableDao().deleteInTx(list);
        }
    }

    public void deleteNoticeTable(String userId) {
        List<SysNoticeTable> list = DbController.getInstance().getRead().getSysNoticeTableDao().queryBuilder().list();
        if (list != null && !list.isEmpty()) {
            for (SysNoticeTable chatTable : list) {
                if (chatTable.getUserId().equals(userId)) {
                    DbController.getInstance().getWrite().delete(chatTable);
                }
            }
        }
    }

    public void deleteNoticeTableByNoticeId(String noticeId) {
        List<SysNoticeTable> list = DbController.getInstance().getRead().getSysNoticeTableDao().queryBuilder().list();
        if (list != null && !list.isEmpty()) {
            for (SysNoticeTable chatTable : list) {
                if (chatTable.getNotifyId().equals(noticeId)) {
                    DbController.getInstance().getWrite().delete(chatTable);
                }
            }
        }
    }

    public void deleteLengthMsgTable(String fromId) {
        List<LengthMessageTable> list = DbController.getInstance().getRead().getLengthMessageTableDao().queryBuilder()
                .where(ChatTableBeanDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).list();
        if (list != null && !list.isEmpty()) {
            DbController.getInstance().getWrite().getLengthMessageTableDao().deleteInTx(list);
        }
    }

    public void deleteVisitorAll(OnDeleteFinishListener listener) {
        if (ChatApp.getInstance().isRegister()) {
            if (listener != null) {
                listener.onFinish(Canstants.CLEAR_TIME,false);
            }
            return;
        }
        deleteUuu(listener);
    }

    public void deleteUuu(OnDeleteFinishListener listener) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Integer>() {
            @Override
            public void onAction(Integer obj) {
                JLog.d("---delete visitor---");
                if (listener != null) {
                    listener.onFinish(Canstants.CLEAR_TIME,true);
                }
            }

            @Override
            public Integer onThreadAction() {
                try {
                    deleteVisitorUser();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    /**
     * 1、清理时机（半夜、息屏、启动）
     * 2、清理位置（登录成功后）
     *
     * @param context
     */
    public void clear(Context context, OnDeleteFinishListener listener) {
        boolean isEveryDayClear = (boolean) SharedUserUtils.get(context, Canstants.getClearKey(), false);
        int cyc = (int) SharedUserUtils.get(context, Canstants.getSysClearCycKey(), 0);
        if (isEveryDayClear) {
            deleteChatAll(listener, Canstants.CLEAR_TIME);
            return;
        }
        if (cyc == 0) {
            deleteChatAll(listener, Canstants.CLEAR_DAY);
        } else if (cyc == 1) {
            deleteChatAll(listener, Canstants.CLEAR_WEEK);
        } else if (cyc == 2) {
            deleteChatAll(listener, Canstants.CLEAR_MONTH);
        }


    }

    public void deleteUser(String targetId) {
        UserTableBean.deleteByUserId(targetId);
        deleteNavChat(targetId, 0, true, true);
    }

    /**
     * 删除聊天记录
     *
     * @param listener
     */
    public void deleteChatAll(OnDeleteFinishListener listener, int duration) {
        //        AlbumUtils.clearAll(ChatApp.getInstance(), ChatApp.getInstance().getPackageName(), ChatApp.getInstance().getUserId());
        if (duration != Canstants.CLEAR_TIME) {
            int cycDay = (int) SharedUserUtils.get(ChatApp.getInstance(), Canstants.getSysClearCycTimeKey(), 0);
            int curtDay = Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
            if (cycDay == 0L || curtDay - cycDay < 0) {
                SharedUserUtils.put(ChatApp.getInstance(), Canstants.getSysClearCycTimeKey(), curtDay);
                if (listener != null) {
                    listener.onFinish(duration,false);
                }
                return;
            }
            if ((curtDay - cycDay >= 1 && duration == Canstants.CLEAR_DAY)
                    || (curtDay - cycDay >= 7 && duration == Canstants.CLEAR_WEEK)
                    || (curtDay - cycDay >= 30 && duration == Canstants.CLEAR_MONTH)) {
            } else {
                if (listener != null) {
                    listener.onFinish(duration,false);
                }
                return;
            }
        }
        if (TextUtils.isEmpty(ChatApp.getInstance().getUserId())) {
            if (listener != null) {
                listener.onFinish(duration,false);
            }
            return;
        }
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Integer>() {
            @Override
            public void onAction(Integer obj) {
                SharedUserUtils.remove(ChatApp.getInstance(), Canstants.getSysClearCycTimeKey());
                if (listener != null) {
                    listener.onFinish(duration,true);
                    JLog.d("--clear--");
                }
            }

            @Override
            public Integer onThreadAction() {
                try {
                    deleteChatHistory();
                    AlbumUtils.clearAll(ChatApp.getInstance(), ChatApp.getInstance().getPackageName(), ChatApp.getInstance().getUserId());
                } catch (Exception e) {
                }
                return null;
            }
        });
    }

    public void deleteAllTable() {
        DbController.getInstance().getWrite().deleteAll(FriendTable.class);
        DbController.getInstance().getWrite().deleteAll(GroupTable.class);
        DbController.getInstance().getWrite().deleteAll(BusinessLeaveTable.class);
        DbController.getInstance().getWrite().deleteAll(GroupMemberTable.class);
        DbController.getInstance().getWrite().deleteAll(SysNoticeTable.class);
        DbController.getInstance().getWrite().deleteAll(LengthMessageTable.class);
        DbController.getInstance().getWrite().deleteAll(UserTableBean.class);
        DbController.getInstance().getWrite().deleteAll(AlbumTableBean.class);
        DbController.getInstance().getWrite().deleteAll(ChatContentTable.class);
        DbController.getInstance().getWrite().deleteAll(ChatTableBean.class);
        SharedUtils.clear(ChatApp.getInstance());
        AlbumUtils.clearAll(ChatApp.getInstance(), ChatApp.getInstance().getPackageName(), ChatApp.getInstance().getUserId());
    }

    public interface OnDeleteFinishListener {
        void onFinish(int clearCyc,boolean isClear);
    }
}
